# -*- coding: utf-8 -*-
from PIL import Image
import matplotlib.pyplot as plt
from skimage import transform
from scipy import stats,signal,fftpack,ndimage,misc
import numpy as np
import numpy.fft as fp
from skimage import io,color

#1.1上采样
#最近邻法上采样----效果比较差
#img=Image.open('F:\\python练习\\图像实战练习\\images\\clock.png')
#img.show()
#将宽和高放大原来的5倍
#img1=img.resize((img.width*5,img.height*5),Image.NEAREST)
#img1.show()

#双线性插值采样----上采样
#img2=img.resize((img.width*5,img.height*5),Image.BILINEAR)
#img2.show()

#双三次插值--上采样
#img3=img.resize((img.width*5,img.height*5),Image.BICUBIC)
#img3.show()

#1.2下采样
im=Image.open('F:\\python练习\\图像实战练习\\images\\tajmahal.jpg')
#im_small=im.resize((im.width//5,im.height//5))
#plt.imshow(im_small)

#抗混叠---高质量的下采样滤波器（ANTIALIAS)
#im_small1=im.resize((im.width//5,im.height//5),Image.ANTIALIAS)
#im_small1.show()

#使用scikit-image中的rescale()解决混叠问题
#im_1=Image.open('F:\\python练习\\图像实战练习\\images\\umbc.png')
#im_2=np.array(im_1).copy()
#plt.figure(figsize=(13,10))
#for i in range(4):
#    plt.subplot(2,2,i+1),plt.imshow(im_2,cmap='gray'),plt.axis('off')
#    plt.title('image size='+str(im_2.shape[1])+'x'+str(im_2.shape[0]))
#    im_2=transform.rescale(im_2,scale=0.5,multichannel=True,anti_aliasing=True)
#plt.subplots_adjust(wspace=0.1,hspace=0.1)
#plt.show()

#PIL量化
#颜色量化----convert---信噪比----stats---signaltonoise()
#在这个版本已经被移除了---signaltonoise
#def signaltonoise(a, axis, ddof):
#    a = np.asanyarray(a)
#    m = a.mean(axis)
#    sd = a.std(axis = axis, ddof = ddof)
#    return np.where(sd == 0, 0, m / sd)
#img_yu=Image.open('F:\\python练习\\图像实战练习\\images\\parrot.jpg')
#plt.figure(figsize=(10,17))
#color_list=[1<<n for n in range(8,0,-1)]
#snr_list=[]
#i=1
#for num in color_list:
#    img_11=img_yu.convert('P',palette=Image.ADAPTIVE,colors=num)
#    plt.subplot(4,2,i),plt.imshow(img_11),plt.axis('off')
#    snr_list.append(signaltonoise(img_11,axis=None))
#    plt.title('Image with # colors=' +str(num)+' SNR='+str(np.round(snr_list[i-1],3)),size=15)    
#    i+=1
#plt.subplots_adjust(wspace=0.2,hspace=0)
#plt.show()

##绘制颜色量化与图像信躁之间关系的图形，信噪比越高，图像质量越好
#plt.plot(color_list,snr_list,'r.-')
#plt.xlabel('Max# colors in the image')
#plt.ylabel('SNR')
#plt.title('Change in SNR')
#plt.xscale('log',basex=2)
#plt.gca().invert_xaxis()
#plt.show()

#2.2离散傅里叶变换
#1.FFT的scipy.fftpack模块----计算DFT/IDFT
#ig=np.array(Image.open('F:\\python练习\\图像实战练习\\images\\rhino.jpg').convert('L'))
#调用上面的signaltonoise函数
#snr=signaltonoise(ig,axis=None,ddof=0)#2.7734186458793535
#fre=fftpack.fft2(ig)
#ig2=fftpack.ifft2(fre).real
#plt.imshow()
#snr=signaltonoise(ig2,axis=None,ddof=0)#2.7734186458793544
#plt.figure(figsize=(15,10))
#plt.subplot(121),plt.imshow(ig,cmap='gray'),plt.axis('off')
#plt.title('org',size=20)
#plt.subplot(122),plt.imshow(ig2,cmap='gray'),plt.axis('off')
#plt.title('rebuild',size=20)
#plt.show()

#绘制凭频谱图
#freq=fftpack.fftshift(fre)
#plt.figure(figsize=(10,10)),plt.imshow((20*np.log10(0.1+freq)).astype(int)),plt.show()

#2.FFT的 numpy.fft模块---计算图像的DFT
#计算DFT的幅值和相位
#def img(image):
#    ih=color.rgb2gray(io.imread(image))
#    freq1=fp.fft2(ih)
#    ih_=fp.ifft2(freq1).real
#    return ih,freq1,ih_
#    
#it=img('F:\\python练习\\图像实战练习\\images\\house.png')
#ihh=img('F:\\python练习\\图像实战练习\\images\\house2.png') 
#plt.figure(figsize=(12,10))
#plt.subplot(2,2,1),plt.imshow(it[0],cmap='gray'),plt.title('original',size=20)
#plt.subplot(2,2,2),plt.imshow(20*np.log10(0.01+np.abs(fp.fftshift(ihh[1]))),cmap='gray')
#plt.title('fft',size=20)
#plt.subplot(2,2,3),plt.imshow(np.angle(fp.fftshift(ihh[1])),cmap='gray')
#plt.title('FFT Phase',size=20)
#plt.subplot(2,2,4),plt.imshow(np.clip(ihh[2],0,255),cmap='gray')
#plt.title('Reconstructed',size=20)
#plt.show()

##观察重建输出的图像是如何变得扭曲的
#plt.figure(figsize=(10,10))
#iu_=fp.ifft2(np.vectorize(complex)(it[1].real,ihh[1].imag)).real
#iu1_=fp.ifft2(np.vectorize(complex)(ihh[1].real,it[1].imag)).real
#plt.subplot(211),plt.imshow(np.clip(iu_,0,255),cmap='gray')
#plt.title('Reconstru(Re(F1)+Im(F2))',size=20)
#plt.subplot(212),plt.imshow(np.clip(iu1_,0,255),cmap='gray')
#plt.title('Reconstru(Re(F2)+Im(F1))',size=15)
#plt.show()

#2.3理解卷积
#对灰度图像应用卷积----1.拉普拉斯检测边缘---2.box方框核模糊图像
#mh=color.rgb2gray(io.imread('F:\\python练习\\图像实战练习\\images\\cameraman.jpg')).astype(float)    
##print(np.max(mh))
#blur_box=np.ones((3,3))/9
#edg_laplace=np.array([[0,1,0],[1,-4,1],[0,1,0]])
#im_blurred=signal.convolve2d(mh,blur_box)
#im_edges=np.clip(signal.convolve2d(mh,edg_laplace),0,1)
#fig,axes=plt.subplots(ncols=3,sharex=True,sharey=True,figsize=(18,6))
#
#axes[0].imshow(mh,cmap=plt.cm.gray)
#axes[0].set_title('Original',size=20)
#axes[1].imshow(im_blurred,cmap=plt.cm.gray)
#axes[1].set_title('Box blur',size=20)
#axes[2].imshow(im_edges,cmap=plt.cm.gray)
#axes[2].set_title('laplace edge',size=20)
#
#for ax in axes:
#    ax.axis('off')
#plt.show()

#彩色图像的卷积----scipy.convolve2d锐化彩色图像---对每个图像通道分别进行卷积
#使用emboss核和schar边缘检测复杂核对图像进行卷积
#dg=io.imread('F:\\python练习\\图像实战练习\\images\\tajmahal.jpg')/255
#emboss_kernel=np.array([[-2,-1,0],[-1,1,1],[0,1,2]])
#edge_kernel=np.array([[-3-3j,0-10j,+3 -3j],[-10+0j,0+ 0j,+10+0j],[-3+3j,0+10j,+3 +3j]])
#im_embossed=np.ones(dg.shape)
#im_edges=np.ones(dg.shape)
#for i in range(3):
#    im_embossed[...,i]=np.clip(signal.convolve2d(dg[...,i],emboss_kernel,mode='same',
#               boundary="symm"),0,1)
#for i in range(3):
#    im_edges[...,i]=np.clip(np.real(signal.convolve2d(dg[...,i],edge_kernel,mode='same',
#               boundary="symm")),0,1)
#
#fig,axes=plt.subplots(ncols=3,figsize=(15,30))
#
#axes[0].imshow(dg)
#axes[0].set_title('Original',size=20)
#axes[1].imshow(im_embossed)
#axes[1].set_title('embossed',size=20)
#axes[2].imshow(im_edges)
#axes[2].set_title('Edge ',size=20)
#
#for ax in axes:
#    ax.axis('off')
#plt.show()
    
#2.3.3 使用scipy中的ndimage.convolve进行卷积-----可直接进行锐化
#dz=io.imread('F:\\python练习\\图像实战练习\\images\\vic.png').astype(np.float)    
#kr=np.array([0,-1,0,-1,5,-1,0,-1,0]).reshape((3,3,1))
#eb_kr=np.array(np.array([[-2,-1,0],[-1,1,1],[0,1,2]])).reshape((3,3,1))
#shr=ndimage.convolve(dz,kr,mode='nearest')
#shr=np.clip(shr,0,255).astype(np.uint8)
#eb=ndimage.convolve(dz,eb_kr,mode='nearest')
#eb=np.clip(eb,0,255).astype(np.uint8)
#
#plt.figure(figsize=(10,15))
#plt.subplot(311),plt.imshow(dz.astype(np.uint8)),plt.axis('off')
#plt.title('Origibal Image',size=25)
#plt.subplot(312),plt.imshow(shr),plt.axis('off')
#plt.title('Sharpened Image',size=25)
#plt.subplot(313),plt.imshow(eb),plt.axis('off')
#plt.title('Embossed Image',size=25)
#plt.tight_layout()
#plt.show()

#2.3.4相关与卷积----scipy--convolution2d()和corrrelation2d
#模板匹配与图像和模板之间的相关性
#face_image=misc.face(gray=True)-misc.face(gray=True).mean()
#template_image=np.copy(face_image[300:365,670:750])#右眼
#template_image_=template_image.mean()

##增加随机噪声
#face_image=face_image+np.random.randn(*face_image.shape)*50
#correlation=signal.correlate2d(face_image,template_image,boundary='symm',mode='same')
##找到匹配
#y,x=np.unravel_index(np.argmax(correlation),correlation.shape)
#
#fig,(ax_original,ax_template,ax_correlation)=plt.subplots(3,1,figsize=(6,15))
#ax_original.imshow(face_image,cmap='gray')
#ax_original.set_title('Original',size=20)
#ax_original.set_axis_off()
#
#ax_template.imshow(template_image,cmap='gray')
#ax_template.set_title('Template',size=20)
#ax_template.set_axis_off()
#
#ax_correlation.imshow(correlation,cmap='gray')
#ax_correlation.set_title('correlation',size=20)
#ax_correlation.set_axis_off()
#
#ax_original.plot(x,y,'ro')
#fig.show()



